import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { Layout, Menu } from 'antd';
import { history } from 'umi';
import styles from './index.less';

const { Sider, Content } = Layout;

const BasicLayout = (props) => {
  const {
    route: { routes },
    location: { pathname },
  } = props;

  // 菜单
  const [menuList, setMenuList] = useState([]);

  // 跳转路由
  const handelMenuClick = (e) => {
    const url = e?.item?.props?.path;
    if (url) history.push(url);
  };

  // 递归处理路由数据
  const getMenuList = (arr) => {
    return _.map(arr, (item) => {
      const { key, path, name, routes } = item;
      const children = _.filter(routes, 'name');
      return {
        key: path || key,
        label: name,
        title: name,
        path,
        children: _.size(children) ? getMenuList(children) : null,
      };
    });
  };

  useEffect(() => {
    const dealMenuList = getMenuList(routes);
    setMenuList(dealMenuList);
  }, []);

  return (
    <Layout>
      <Sider className={styles.sider} collapsible theme="light" trigger={null}>
        <Menu
          defaultOpenKeys={['decEcoTesting']}
          defaultSelectedKeys={[pathname]}
          mode="inline"
          theme="light"
          items={menuList}
          onClick={handelMenuClick}
        />
      </Sider>
      <Layout className={styles.layOut}>
        <Content style={{ margin: '24px 24px 0', height: '100%' }}>
          {props.children}
        </Content>
      </Layout>
    </Layout>
  );
};

export default BasicLayout;
